package cn.edu.zstu.qingzhu.qingzhushop.handler;

import cn.edu.zstu.qingzhu.qingzhushop.entity.Log;
import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import cn.edu.zstu.qingzhu.qingzhushop.service.ILogService;
import cn.edu.zstu.qingzhu.qingzhushop.util.IPUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

/**
 * @Author ShenTuZhiGang
 * @Version 1.0.0
 * @Date 2020-03-21 16:48
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Autowired
    ILogService iLogService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException, ServletException {
        String ip = IPUtil.getIPAddress(httpServletRequest);
        String username = httpServletRequest.getParameter("username");
        Log loginLog = new Log();
        loginLog.setOperation("登录");
        loginLog.setType("login");
        loginLog.setIp(ip);
        loginLog.setOperator(username);
        loginLog.setTime(LocalDateTime.now());
        loginLog.setStatus("failure");
        loginLog.setRemark("登录失败:" + e.getMessage());
        //iLogService.save(loginLog);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ResponseBean retTemp = new ResponseBean.Builder()
                .setStatus(400)
                .setMsg("登录失败:" + e.getMessage())
                .build();
        PrintWriter out = httpServletResponse.getWriter();
        out.write(new ObjectMapper().writeValueAsString(retTemp));
        out.flush();
        out.close();
    }
}
